package com.liukai.todo_android.presenter;

import com.liukai.todo_android.common.utils.RetrofitManager;
import com.liukai.todo_android.common.api.UserApi;
import com.liukai.todo_android.common.base.BasePresenter;
import com.liukai.todo_android.call_back.ILoginCallBack;
import com.liukai.todo_android.entity.vo.LoginVO;
import com.liukai.todo_android.entity.Resp;

import java.net.HttpURLConnection;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

/**
 * @author ：liukai
 * @date ：Created in 2021/8/8 2:35 下午
 * @description：登录相关的presenter层
 * @modified By：
 * @version: $
 */
public class LoginPresenter extends BasePresenter<ILoginCallBack> {

    /**
     * 登录的具体实现
     *
     * @param loginVO
     */
    public void login(LoginVO loginVO) {
        Retrofit retrofit = RetrofitManager.getInstance().getRetrofit();
        UserApi userApi = retrofit.create(UserApi.class);
        Call<Resp> loginTask = userApi.login(loginVO);
        loginTask.enqueue(new Callback<Resp>() {
            @Override
            public void onResponse(Call<Resp> call, Response<Resp> response) {
                int code = response.code();
                if (code == HttpURLConnection.HTTP_OK) {
                    // 登录成功
                    Resp body = response.body();
                    if (body.getCode() == 200) {
                        mCallBack.loginSuccess(body);
                    } else {
                        mCallBack.loginError(body);
                    }
                } else {
                    // 登录失败
                    mCallBack.loginError(Resp.err("登录失败，请重新登录"));
                }
            }

            @Override
            public void onFailure(Call<Resp> call, Throwable t) {
                mCallBack.loginError(Resp.err("请求失败，请检查网络是否连接！"));
            }
        });
    }

}
